<template>
  <div class="image-list">
    <!--
        如果给按钮注册点击事件的话，会导致每次发送2次请求，
        正确的方式是使用组件提供的change事件
      -->
    <div class="artion-head">
      <el-radio-group v-model="collect" size="mini" @change="onCollectChange">
        <el-radio-button :label="false">全部</el-radio-button>
        <el-radio-button :label="true">收藏</el-radio-button>
      </el-radio-group>
      <el-button
        type="success"
        size="mini"
        @click="dialogUploadVisible = true"
        v-if="isShowAdd"
        >上传素材</el-button
      >
    </div>
    <el-row :gutter="10">
      <el-col
        :lg="4"
        :md="4"
        :sm="6"
        :xs="12"
        v-for="(image, index) in images"
        :key="index"
        class="image-item"
        @click.native="selected = index"
      >
        <el-image
          style="width: 100px; height: 100px"
          :src="image.url"
          fit="cover"
        ></el-image>
        <div class="selected" v-if="isShowSelected && selected === index"></div>
        <div class="image-action" v-if="isShowAction">
          <!--
            class 样式绑定
            {
              css类名: 绑定值（true作用类名，false不作用类名）
            }
          -->
          <el-button
            :loading="image.loading"
            class="collect-btn"
            :icon="image.is_collected ? 'el-icon-star-on' : 'el-icon-star-off'"
            circle
            @click="onCollect(image)"
            size="mini"
          ></el-button>
          <el-button
            class="collect-btn"
            :loading="image.loading"
            icon="el-icon-delete"
            circle
            size="mini"
            @click="onDelImage(image)"
          ></el-button>
          <!-- <i
              v-loading="imageLoad"
              :class="{
                'el-icon-star-on': image.is_collected,
                'el-icon-star-off': !image.is_collected,
              }"
              @click="onCollect(image)"
            ></i>
             -->
          <!-- <i class="el-icon-delete"></i> -->
        </div>
      </el-col>
    </el-row>
    <!--  分页 -->
    <el-pagination
      background
      :page-size="pageSize"
      layout="prev, pager, next"
      :current-page.sync="page"
      @current-change="onPageChange"
      :total="totalCount"
    >
    </el-pagination>
    <!--
      :show-file-list="false"：不展示上传素材对话框中的图片上传历史
      :visible.sync="dialogUploadVisible"：显示或关闭对话框
      :append-to-body="true"：将对话框中的内容显示到body层
    -->
    <!-- 上传素材 -->
    <!--
      :show-file-list="false"：不展示上传素材对话框中的图片上传历史
      :visible.sync="dialogUploadVisible"：显示或关闭对话框
      :append-to-body="true"：将对话框中的内容显示到body层
    -->
    <el-dialog
      title="上传素材"
      :visible.sync="dialogUploadVisible"
      :append-to-body="true"
    >
      <!--
        upload 组件本身就支持请求提交上传操作
        所以不用自己单独发送上传请求
        请求方法：默认POST
        请求路径：action指定完整的文件上传接口地址
        请求头：headers
      -->
      <el-upload
        v-if="dialogUploadVisible"
        class="upload-demo"
        drag
        action="http://api-toutiao-web.itheima.net/mp/v1_0/user/images"
        multiple
        name="image"
        :headers="uploadHeader"
        :on-success="onUpdateSuccess"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          只能上传jpg/png文件，且不超过500kb
        </div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import { getImages, collectImage, delImage } from '@/api/image'
export default {
  name: 'ImageList',
  components: {},
  props: {
    isShowAdd: {
      type: Boolean,
      default: true
    },
    isShowAction: {
      type: Boolean,
      default: true
    },
    isShowSelected: {
      type: Boolean,
      default: false
    }
  },
  data () {
    const { user } = this.$store.state
    return {
      collect: false,
      images: [],
      dialogUploadVisible: false,
      uploadHeader: {
        Authorization: `Bearer ${user.token}`
      },
      totalCount: 0, // 图片总数
      pageSize: 12, // 每页大小
      page: 1,
      selected: null // 选中的索引
    }
  },
  computed: {},
  watch: {},
  mounted () {
    this.loadImage(1, false)
  },
  methods: {
    async loadImage (page = 1) {
      this.page = page
      const { data } = await getImages({
        collect: this.collect,
        page,
        per_page: this.pageSize
      })
      // console.log(data)
      const results = data.data.results
      // 遍历数组
      results.forEach(img => {
        // 往img对象中添加loading变量记录每个图片的loading状态
        img.loading = false
      })
      this.images = data.data.results
      this.totalCount = data.data.total_count
    },
    onCollectChange () {
      this.loadImage(1)
    },
    onUpdateSuccess () {
      // 关闭对话框
      this.dialogUploadVisible = false
      // 跟新素材列表
      this.loadImage(this.page)
      this.$message({
        type: 'success',
        message: '上传成功'
      })
    },
    onPageChange (page) {
      this.loadImage(page)
    },
    //  收藏图片
    onCollect (image) {
      // 展示loading
      image.loading = true
      try {
        collectImage(image.id, !image.is_collected)
        // 手动修改收藏图标状态
        image.is_collected = !image.is_collected
        image.loading = false
        this.$message({
          message: image.is_collected ? '取消收藏成功' : '收藏成功',
          type: 'success'
        })
      } catch (error) {

      }
      // // 判断是否是收藏状态
      // if (image.is_collected) {
      //   // 已收藏，取消收藏
      //   collectImage(image.id, false)
      // } else {
      //   collectImage(image.id, true)
      // }
    },
    // 删除图片
    async onDelImage (image) {
      image.loading = true
      try {
        // 删除图片
        await delImage(image.id)
        // 更新素材列表
        this.loadImage(this.page)
        image.loading = false
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      } catch (error) {

      }
    }
  }
}
</script>

<style scoped lang="less">
.artion-head {
  padding-bottom: 20px;
  display: flex;
  justify-content: space-between;
}
.image-item {
  position: relative;
}
.image-action {
  font-size: 20px;
  display: flex;
  justify-content: space-evenly;
  align-content: center;
  color: #fff;
  width: 100px;
  height: 28px;
  background-color: rgba(208, 208, 208, 0.5);
  position: absolute;
  bottom: 4px;
  left: 5px;
  right: 5px;
}
// .collect-btn {
//   height: 15px;
//   width: 15px;
//   border-radius: 50%;
// }

.selected {
  background: url(./selected.png) no-repeat;
  background-size: cover;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
